from flask import Flask, render_template, request, jsonify, Response
import os
import json
from prompt import prompt
from deepseek_api import DeepSeekAPI
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

app = Flask(__name__)

# 初始化DeepSeek API客户端
api_client = DeepSeekAPI()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
def generate_questions():
    try:
        data = request.get_json()
        course_name = data.get('course_name')
        question_types = data.get('question_types')
        num_questions = data.get('num_questions')
        knowledge_content = data.get('knowledge_content')
        
        # 构建提示词
        formatted_prompt = prompt.format(
            course_name=course_name,
            question_types=question_types,
            num_questions=num_questions,
            knowledge_content=knowledge_content
        )
        
        def generate():
            try:
                # 调用DeepSeek API生成题目
                for progress_data in api_client.generate_questions(formatted_prompt):
                    if isinstance(progress_data, dict):
                        # print(progress_data)
                        # 检查是否有错误信息
                        if 'error' in progress_data:

                            yield f"data: {json.dumps({'error': progress_data['error']})}\n\n"
                            return
                        yield f"data: {json.dumps(progress_data)}\n\n"
            except Exception as e:
                error_msg = f"生成题目时发生错误: {str(e)}"
                yield f"data: {json.dumps({'error': error_msg})}\n\n"
        
        return Response(generate(), mimetype='text/event-stream')
    
    except Exception as e:
        raise e
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':

    app.run(debug=True)